/*
 * @lc app=leetcode.cn id=61 lang=javascript
 *
 * [61] 旋转链表
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} k
 * @return {ListNode}
 */
var rotateRight = function (head, k) {
  if (!head) return null;

  const dummy = new ListNode(0, head);
  let length = 0;
  let lastNode;
  while (head) {
    length++;
    lastNode = head;
    head = head.next;
  }

  let times = k % length;
  if (times === 0) return dummy.next;

  let pre = dummy;
  for (let i = 0; i < length - times; i++) pre = pre.next;
  head = pre.next;
  pre.next = null;
  lastNode.next = dummy.next;

  return head;
};
// @lc code=end
